//
//  NearListViewController.swift
//  HyphenateIMDemo
//
//  Created by Shang Hai Rui Xi on 2019/3/8.
//  Copyright © 2019 Shang Hai Rui Xi. All rights reserved.
//

import UIKit
import Hyphenate

class NearListViewController: UIViewController {

    public var tableView: UITableView?
    internal var conversations: [EMConversation] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        registerNotifications()
        setUpUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getConversations()
    }
    
    deinit {
        unregisterNotifications()
    }
}

extension NearListViewController {
    private func getConversations() {
        if let conversations = EMClient.shared()?.chatManager.getAllConversations() as? [EMConversation] {
            refreshAndSort(conversations: conversations)
        }
    }
    
    //MARK: 刷新进行排序
    private func refreshAndSort(conversations: [EMConversation]) {
        if conversations.count <= 0 { return }
        let sortedConversations = conversations.sorted { (conversation1, conversation2) -> Bool in
            return conversation1.latestMessage.timestamp > conversation2.latestMessage.timestamp
        }
        self.conversations.removeAll()
        self.conversations.append(contentsOf: sortedConversations)
        self.tableView?.reloadData()
    }
}

// MARK: - tableView TableViewDelegate和TableViewDataSource代理
extension NearListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return conversations.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 75
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "consationCellId") as! EMConversationViewCell
        cell.conversation = conversations[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let conversation = conversations[indexPath.row]
        let chatVc = ChatViewController.init(conversation: conversation)
        chatVc.title = conversation.conversationId
        chatVc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(chatVc, animated: true)
    }
    
}

//MARK: Notifications, EMChatManagerDelegate
extension NearListViewController: EMChatManagerDelegate {
    //MARK: 收到消息
    func messagesDidReceive(_ aMessages: [Any]!) {
        getConversations()
    }
    
    //MARK: 会话列表发生变化
    func conversationListDidUpdate(_ aConversationList: [Any]!) {
        // - 列表变化 重新进行排序
        if let conversations = aConversationList as? [EMConversation] {
            refreshAndSort(conversations: conversations)
        }
    }
    
    private func registerNotifications() {
        EMClient.shared()?.chatManager.add(self, delegateQueue: nil)
    }
    
    private func unregisterNotifications() {
        EMClient.shared()?.chatManager.remove(self)
    }
}

extension NearListViewController {
    private func setUpUI() {
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView?.delegate   = self
        tableView?.dataSource = self
        tableView?.backgroundColor = UIColor.hexadecimalColor(hex: 0xFAFAFA)
        tableView?.separatorInset.left = 79
        tableView?.separatorColor = UIColor.hexadecimalColor(hex: 0xE1E1E1)
        view.addSubview(tableView!)
        tableView?.tableFooterView = UIView.init()
        tableView?.register(EMConversationViewCell.self, forCellReuseIdentifier: "consationCellId")
        if #available(iOS 11.0, *) {
            tableView?.estimatedRowHeight = 0
            tableView?.estimatedSectionFooterHeight = 0
            tableView?.estimatedSectionHeaderHeight = 0
        }
    }
}
